export default class SvgSectorMarker {
  constructor(lnglat, options = {}) {
    // 默认配置
    const defaults = {
      startAngle: 0,
      endAngle: 90,
      radius: 40,
      isDirec:false,
      isDrag:false
    };

    this.options = { ...defaults, ...options };
    this.isDirec = this.options.isDirec;
    this.isDrag = this.options.isDrag;
    this.statusEl = this.options.statusEl;
    this.lnglat = lnglat;
    this.map = this.options.map;
    this.moving = false;
    this.rotating = false;
    this.adjusting = null;
    // 创建容器
    this.container = document.createElement("div");
    this.container.className = "sector-container";

    // 创建SVG
    this.svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
    this.svg.setAttribute("class", "sector-svg");
    this.svg.setAttribute("viewBox", "-50 -50 100 100");
    this.container.appendChild(this.svg);
    const markerSize = 100; // 与实际渲染尺寸一致
    const anchorPosition = {
      x: markerSize / 2 + window.devicePixelRatio,
      y: markerSize / 2 + window.devicePixelRatio
    };
    // 创建Mapbox Marker
    this.marker = new mapboxgl.Marker({
      element: this.container,
      anchor: "center", // 关键：将锚点设为容器中心
      // draggable: false // 禁用默认的拖拽
      offset: [anchorPosition.x, anchorPosition.y]
    })
      .setLngLat(lnglat)
      .setDraggable(this.isDrag)
      .addTo(this.map);
    this.marker._this = this;

    // 绑定事件
    this.bindEvents();

    // 初始渲染
    this.render();
    return this.marker;
  }

  render() {
    this.svg.innerHTML = "";
    const { startAngle, endAngle, radius } = this.options;
    // 创建扇形路径
    const sectorPath = this.createSectorPath(startAngle, endAngle, radius);
    sectorPath.setAttribute("class", "sector-path");
    // sectorPath.dataset.type = 'move'
    this.svg.appendChild(sectorPath);

    // 创建中心点
    const centerPoint = (this.centerPoint = document.createElementNS(
      "http://www.w3.org/2000/svg",
      "circle"
    ));
    centerPoint.setAttribute("class", "center-point");
    centerPoint.setAttribute("cx", 0);
    centerPoint.setAttribute("cy", 0);
    this.svg.appendChild(centerPoint);
    // 创建移动手柄 (蓝色)
    // const moveHandle = document.createElementNS(
    //   "http://www.w3.org/2000/svg",
    //   "circle"
    // );
    // moveHandle.setAttribute("class", "camera-point");
    // moveHandle.setAttribute("cx", 0);
    // moveHandle.setAttribute("cy", 0);
    // // moveHandle.dataset.type = "move";
    // this.svg.appendChild(moveHandle);

    // 创建旋转手柄 (绿色)
    const rotateHandle = document.createElementNS(
      "http://www.w3.org/2000/svg",
      "circle"
    );
    rotateHandle.setAttribute("class", "rotate-handle");
    rotateHandle.dataset.type = "rotate";
    let midAngle = (startAngle + endAngle) / 2;
    if(endAngle - startAngle > 180) {
      midAngle = (startAngle + endAngle-360) / 2;
    }
    const rad = (midAngle - 90) * Math.PI / 180;
    
    // 计算手柄坐标
    const handleX = radius * 0.9 * Math.cos(rad);
    const handleY = radius * 0.9 * Math.sin(rad);
    
    // 应用位置变换（示例：使用<circle>作为手柄）
    rotateHandle.setAttribute("cx", handleX);
    rotateHandle.setAttribute("cy", handleY);
    this.svg.appendChild(rotateHandle);

    // 创建角度手柄 (白色带蓝边)
    const startHandle = this.createAngleHandle(startAngle, radius, "start");
    const endHandle = this.createAngleHandle(endAngle, radius, "end");
    this.svg.appendChild(startHandle);
    this.svg.appendChild(endHandle);

    // 应用整体旋转
    // this.svg.style.transform = `rotate(${rotation}deg)`;
  }

  createSectorPath(start, end, radius) {
    const path = document.createElementNS("http://www.w3.org/2000/svg", "path");
    // console.log('start',start,end)
    // 1️⃣ 规范化角度到0-360°
    start = ((start % 360) + 360) % 360;
    end = ((end % 360) + 360) % 360;

    // 2️⃣ 计算顺时针角度差
    let angleDiff = (end - start + 360) % 360; // 处理跨0°线情况

    // 3️⃣ 角度差>180°时：取补角（360° - angleDiff）
    if (angleDiff > 180) {
      // 4️⃣ 从结束角顺时针画到起始角（补角方向）
      const startRad = ((end - 90) * Math.PI) / 180; // 结束角作为新起点
      const endRad = ((start - 90) * Math.PI) / 180; // 起始角作为新终点

      // 5️⃣ 构建顺时针补角扇形路径
      let d = `M 0 0 `;
      d += `L ${radius * Math.cos(startRad)} ${radius * Math.sin(startRad)} `;
      d += `A ${radius} ${radius} 0 0 1 `; // 顺时针大弧线（large-arc=1）
      d += `${radius * Math.cos(endRad)} ${radius * Math.sin(endRad)} `;
      d += "Z";
      path.setAttribute("d", d);
    }
    // 6️⃣ 角度差≤180°：正常顺时针绘制
    else {
      const startRad = ((start - 90) * Math.PI) / 180;
      const endRad = ((end - 90) * Math.PI) / 180;

      let d = `M 0 0 `;
      d += `L ${radius * Math.cos(startRad)} ${radius * Math.sin(startRad)} `;
      d += `A ${radius} ${radius} 0 ${angleDiff > 180 ? 1 : 0} 1 `; // 顺时针弧线
      d += `${radius * Math.cos(endRad)} ${radius * Math.sin(endRad)} `;
      d += "Z";
      path.setAttribute("d", d);
    }
    return path;
  }
  createAngleHandle(angle, radius, type) {
    const handle = document.createElementNS(
      "http://www.w3.org/2000/svg",
      "circle"
    );
    handle.setAttribute("class", "angle-handle");
    handle.dataset.type = "angle";
    handle.dataset.angleType = type;

    const rad = ((angle - 90) * Math.PI) / 180;
    const x = radius * Math.cos(rad);
    const y = radius * Math.sin(rad);

    handle.setAttribute("cx", x);
    handle.setAttribute("cy", y);
    return handle;
  }

  bindEvents() {
    this.svg.addEventListener("mousedown", this.handleMouseDown.bind(this));
    document.addEventListener("mousemove", this.handleMouseMove.bind(this));
    document.addEventListener("mouseup", this.handleMouseUp.bind(this));
  }

  handleMouseDown(e) {
    if (!e.target.dataset.type) return;
    this.map.dragPan.disable();
    const type = e.target.dataset.type;
    const angleType = e.target.dataset.angleType;
    const startX = e.clientX;
    const startY = e.clientY;
    this.moving = false;
    this.rotating = false;
    this.adjusting = false;
    // 移动手柄
    // 旋转手柄
    if (type === "rotate") {
      this.rotating = true;
      this.startRotation = this.options.rotation;
      this.statusEl.textContent = "旋转模式";
      this.container.style.cursor = "grabbing";
    }
    // 角度手柄
    else if (type === "angle") {
      this.adjusting = angleType;
      this.startAngle = this.options[`${angleType}Angle`];
      this.statusEl.textContent = `调整${
        angleType === "start" ? "起始" : "结束"
      }角度`;
      this.container.style.cursor = "ew-resize";
    }

    this.startMouseX = startX;
    this.startMouseY = startY;
  }

  handleMouseMove(e) {
    if(!this.isDirec) return;
    if (this.rotating) {
      const pos = this.centerPoint.getBoundingClientRect();
      const centerX = pos.left + pos.width / 2;
      const centerY = pos.top + pos.height / 2;
      // 计算角度变化
      // 同时获取X和Y方向的偏移量
      const dx = e.clientX - centerX;
      const dy = e.clientY - centerY;
      // console.log(dx, dy);
      // 计算鼠标相对于中心点的角度变化（弧度）
      const angleDelta = Math.atan2(dy, dx) * (180 / Math.PI);
      const {endAngle, startAngle} = this.options;
      const diffDelta = Math.abs(endAngle - startAngle) / 2;
      this.options['startAngle'] = angleDelta-diffDelta+90;
      this.options['endAngle'] = angleDelta+diffDelta+90;
      // 计算旋转角度
      // const dx = e.clientX - this.startMouseX;
      // this.options.rotation = (angleDelta + 90 + 360) % 360;
      this.render();
      this.statusEl.innerHTML = `旋转模式: ${this.options.rotation.toFixed(
        1
      )}°`;
    } else if (this.adjusting) {
      const pos = this.centerPoint.getBoundingClientRect();
      const centerX = pos.left + pos.width / 2;
      const centerY = pos.top + pos.height / 2;
      // 计算角度变化
      // 同时获取X和Y方向的偏移量
      const dx = e.clientX - centerX;
      const dy = e.clientY - centerY;
      // console.log(dx, dy);
      // 计算鼠标相对于中心点的角度变化（弧度）
      const angleDelta = Math.atan2(dy, dx) * (180 / Math.PI);
      // 应用角度变化
      const key = `${this.adjusting}Angle`;
      this.options[key] = (angleDelta + 90 + 360) % 360;
      // console.log('angleDelta',angleDelta)
      this.render();
      this.statusEl.innerHTML = `调整${
        this.adjusting === "start" ? "起始" : "结束"
      }角度: ${this.options[key].toFixed(1)}°`;
    }
  }

  handleMouseUp() {
    if (this.moving || this.rotating || this.adjusting) {
      this.moving = false;
      this.rotating = false;
      this.adjusting = null;
      this.container.style.cursor = "default";
      this.statusEl.textContent = "就绪";
    }
    this.map.dragPan.enable();
  }
}